import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/orgs/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../im/im_chat/index.dart';
import 'index.dart';

class PersonController extends GetxController {
  PersonController();

  final state = PersonState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null && map["id"] != null && map["id"] is String) {
      String id = map["id"] as String;
      loadPersonInfo(id);
    } else {
      OLogger.e('参数异常，没有人员 id');
      Get.back();
    }
    super.onReady();
  }

  /// 查询人员信息
  loadPersonInfo(String id) async {
    Loading.show();
    final person = await OrganizationControlService.to.person(id);
    if (person != null) {
      Loading.dismiss();
      if (person.superior != null && person.superior?.isNotEmpty == true) {
        loadSuperiorName(person.superior!);
      }
      state.person.value = person;
      // 隐藏手机号码
      if (O2ContactPermissionManager.instance
          .isHiddenMobile(person.distinguishedName!)) {
        person.showMobile = O2.hiddenMobileNumber;
      }
      if (person.woIdentityList != null) {
        state.departmentNames =
            person.woIdentityList!.map((e) => e.unitName!).toList().join('、');
      }
      loadPersonAttribute(person.woPersonAttributeList ?? []);
    } else {
      OLogger.e('人员 id $id 查询人员信息失败！');
      Get.back();
    }
  }

  /// 汇报对象人员名称
  loadSuperiorName(String id) async {
    final person = await OrganizationControlService.to.person(id);
    if (person != null) {
      state.superiorName = person.name ?? '';
    }
  }

  /// 加载人员属性
  loadPersonAttribute(List<O2PersonAttribute> woPersonAttributeList) async {
    if (woPersonAttributeList.isEmpty) {
      return;
    }
    List<O2PersonAttribute> personAttributeList = [];
    Map<String, dynamic> extendParam = ProgramCenterService.to.extendParam();
    Map<String, dynamic>? personAttributeMobile = extendParam['personAttributeMobile'];
    if (personAttributeMobile == null) {
      Map<String, dynamic>? config = await O2ApiManager.instance.getWebConfigJson();
      if (config != null  ) {
        personAttributeMobile = config['personAttributeMobile'];
      }
    } 
    List<String> showList =
        personAttributeMobile?['showList']?.cast<String>() ?? [];
    List<String> hiddenList =
        personAttributeMobile?['hiddenList']?.cast<String>() ?? [];
    if (showList.isEmpty && hiddenList.isEmpty) {
      personAttributeList.addAll(woPersonAttributeList);
    } else {
      for (O2PersonAttribute attribute in woPersonAttributeList) {
        if ((showList.isNotEmpty && showList.contains(attribute.name)) ||
            (hiddenList.isNotEmpty && !hiddenList.contains(attribute.name))) {
          personAttributeList.add(attribute);
        }
      }
    }
    state.personAttributeList.addAll(personAttributeList);
  }

  void mailTo(String mail) async {
    if (mail.isNotEmpty) {
      Uri uri = Uri(scheme: 'mailto', path: mail);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri);
      }
    }
  }

  void telTo(String phone) async {
    if (phone.isNotEmpty) {
      Uri uri = Uri(scheme: 'tel', path: phone);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri);
      }
    }
  }

  /// 发起聊天
  Future<void> startSingleChat() async {
    var person = state.person.value;
    if (person != null && person.distinguishedName != null) {
      Loading.show();
      final conv = await MessageCommunicationService.to.createConversation(
          O2.imConversationTypeSingle, [person.distinguishedName!]);
      if (conv != null) {
         Loading.dismiss();
        await ImChatPage.open(conv.id!);
      }
    }
  }
}
